/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.component;

import cn.easyplatform.contexts.ListContext;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dao.BizDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.dos.Record;
import cn.easyplatform.engine.runtime.datalist.DataListUtils;
import cn.easyplatform.entities.beans.list.ListBean;
import cn.easyplatform.entities.beans.table.TableBean;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Lang;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.ActionValueChangedRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.ActionValueChangedVo;
import cn.easyplatform.messages.vos.datalist.ListActionValueChangedVo;
import cn.easyplatform.support.scripting.MappingEngine;
import cn.easyplatform.support.scripting.ScriptEngineFactory;
import cn.easyplatform.support.sql.SqlParser;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class GetActionValueCmd extends
		AbstractCommand<ActionValueChangedRequestMessage> {

	/**
	 * @param req
	 */
	public GetActionValueCmd(ActionValueChangedRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		WorkflowContext ctx = cc.getWorkflowContext();
		ActionValueChangedVo avc = req.getBody();
		ListBean bean = cc.getEntity(avc.getEntityId());
		if (bean == null)
			return MessageUtils.entityNotFound(EntityType.DATALIST.getName(),
					avc.getEntityId());
		TableBean table = null;
		if (!Strings.isBlank(bean.getTable())) {
			table = cc.getEntity(bean.getTable());
			if (table == null)
				return MessageUtils.entityNotFound(EntityType.TABLE.getName(),
						bean.getTable());
		}
		RecordContext rc = null;
		if (avc instanceof ListActionValueChangedVo) {
			ListActionValueChangedVo lavc = (ListActionValueChangedVo) avc;
			ListContext lc = cc.getWorkflowContext().getList(lavc.getId());
			rc = lc.getRecord(lavc.getKeys());
			if (rc == null && lc.getType().equals(Constants.CATALOG)) {
				Record record = DataListUtils.getRecord(cc, lc, lavc.getKeys());
				rc = lc.createRecord(lavc.getKeys(), record);
				lc.appendRecord(rc);
			}
			if (rc == null)
				return MessageUtils.recordNotFound(lc.getBean().getTable(),
						Lang.concat(lavc.getKeys()).toString());
			if (rc.getParameterAsChar("814") != 'C')
				rc.setParameter("814", 'U');
			rc.setParameter("815", Boolean.TRUE);
		} else
			rc = ctx.getRecord();
		FieldDo fd = rc.getField(avc.getTargetName());
		fd.setValue(avc.getValue());
		StringBuilder sb = new StringBuilder();
		if (!Strings.isBlank(bean.getQuery()))
			sb.append(bean.getQuery()).append(" where ");
		else
			sb.append("select * from ").append(table.getId()).append(" where ");
		List<FieldDo> params = null;
		if (!Strings.isBlank(bean.getCondition())) {
			SqlParser<FieldDo> sp = RuntimeUtils.createSqlParser(FieldDo.class);
			sb.append("(").append(sp.parse(bean.getCondition(), rc));
			params = sp.getParams();
			sb.append(") and ");
		} else
			params = new ArrayList<FieldDo>();
		params.add(new FieldDo(avc.getSourceName(), fd.getType(), avc
				.getValue()));
		sb.append(avc.getSourceName()).append("=?");
		BizDao dao = cc.getBizDao(table == null ? null : table.getSubType());
		FieldDo[] data = dao.selectOne(sb.toString(), params);
		if (data == null)
			return new SimpleResponseMessage();
		MappingEngine engine = ScriptEngineFactory.createMappingEngine();
		List<String> list = engine.eval(cc, rc, data, avc.getMapping());
		return new SimpleResponseMessage(list.toArray(new String[list.size()]));
	}

}
